﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI;
using viBlog.Classes;
using viBlog.Controllers;
using visinia.SmartEngine;
using visinia.SmartEngine.Modules;
using visinia.SmartEngine.Site;

public partial class Modules_viBlog_CommentsList_CommentsList : WebModule
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int postid = 0;
        if (Int32.TryParse(Request.QueryString["PostId"], out postid))
        {
            List<Comment> comments = CommentController.GetComments(postid);
            foreach (Comment comment in comments)
            {
                CommentView commentview = (CommentView)LoadControl(GetCommentView());
                commentview.Comment = comment;
                comment_list.Controls.Add(commentview);
            }

            Post post = PostController.GetPost(postid);
            if (post != null)
            {
                // comment posting is allowed for this post
                if (post.AllowComments)
                {
                    WebPageController.AddScriptLink(Page, WebRoots.GetModulesRoot + "viBlog/CommentsList/CommentForm.js");
                    // for client side comment posting code
                    comment_postid.Value = Request.QueryString["PostId"];
                    comment_form.Visible = true;
                    return;
                }
                string divstr = "<strong>Comments posting closed</strong>";
                LiteralControl divctrl = new LiteralControl(divstr);
                Controls.Add(divctrl);
            }
        }
        else 
        {
            comments_container.Visible = false;
        }    
    }

    private string GetCommentView()
    {
        // search for the CommentView.ascx 
        // 1 search in the current active theme folder
        //   if not found then
        // 2 search in the current folder

        string currentThemeDir = Server.MapPath(WebRoots.GetThemesRoot) + SiteSettings.Theme;
        string file = currentThemeDir + "/viBlog.CommentView.ascx";
        if (File.Exists(file))
            return WebRoots.GetThemesRoot + SiteSettings.Theme + "/viBlog.CommentView.ascx";
        else
            return "viBlog.CommentView.ascx";
    }
}
